﻿using System;
using System.Diagnostics;
using System.Net;
using System.Text;

namespace TestEchart
{
    public class SimpleHttpServer
    {
        private readonly HttpListener _listener;
        // 定义一个事件来处理请求
        public event EventHandler<HttpListenerContext> RequestReceived;

        public SimpleHttpServer(string[] prefixes)
        {

            _listener = new HttpListener();
            foreach (var prefix in prefixes)
            {
                _listener.Prefixes.Add(prefix);
            }

        }

        public void Start()
        {
            _listener.Start();
            while (true)
            {
                try
                {
                    var context = _listener.GetContext();
                    // 触发事件
                    RequestReceived?.Invoke(this, context);

                    // 如果没有外部处理程序，使用默认处理函数
                    if (RequestReceived == null || RequestReceived.GetInvocationList().Length == 0)
                    {
                        DefaultRequestHandler(context);
                    }

                }
                catch
                {
                    // ignored
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }

        private void DefaultRequestHandler(HttpListenerContext context)
        {
            var responseString = "<html><head><title>Default Response</title></head><body>Hello from default handler!</body></html>";
            var buffer = Encoding.UTF8.GetBytes(responseString);
            context.Response.ContentLength64 = buffer.Length;
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.Close();
            Debug.WriteLine("Default request handled!");
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }


    }

    // class Program
    // {
    //     static void Main(string[] args)
    //     {
    //         // 设置基础目录和监听前缀
    //         string baseDirectory = @"C:\path\to\directory";
    //         string[] prefixes = { "http://localhost:8080/" };
    //
    //         // 创建HTTP服务器实例并启动
    //         SimpleHttpServer httpServer = new SimpleHttpServer(baseDirectory, prefixes);
    //         httpServer.Start();
    //
    //         Console.WriteLine("Press any key to stop the server...");
    //         Console.ReadKey();
    //
    //         // 停止服务器
    //         httpServer.Stop();
    //     }
    // }
}